<template>
  <div class="kafka-monitor-container" :style="containerStyle">
    <!-- 页面标题和统计卡片 -->
    <div class="page-header">
      <div class="header-background">
        <div class="bg-pattern"></div>
        <div class="bg-gradient"></div>
      </div>
      
      <div class="page-title">
        <div class="title-icon">
          <div class="icon-container" style="width: 36px; height: 36px; background: linear-gradient(135deg, #ff9800 0%, #ffb74d 100%); border-radius: 8px; color: white; box-shadow: 0 2px 8px rgba(255, 152, 0, 0.2);">
            <el-icon size="20"><Monitor /></el-icon>
            <div class="icon-glow"></div>
          </div>
        </div>
        <div class="title-content">
          <div class="title-main">
            <h1>Kafka监控管理</h1>
            <div class="title-badge">
              <el-icon><Star /></el-icon>
              <span>Monitor</span>
            </div>
          </div>
          <p class="page-description">
            <el-icon><Monitor /></el-icon>
            监控Kafka Topic消息延迟，实时掌握数据流健康状态
          </p>
          <div class="title-meta">
            <div class="meta-item">
              <el-icon><Clock /></el-icon>
              <span>实时监控</span>
            </div>
            <div class="meta-item">
              <el-icon><Bell /></el-icon>
              <span>智能告警</span>
            </div>
            <div class="meta-item">
              <el-icon><Menu /></el-icon>
              <span>数据分析</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="page-stats">
        <div class="stat-card active">
          <div class="stat-icon">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.active_count || 0 }}</div>
            <div class="stat-label">活跃</div>
            <div class="stat-trend">
              <el-icon><Menu /></el-icon>
              <span>正常</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card monitored">
          <div class="stat-icon">
            <el-icon><View /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.monitored_count || 0 }}</div>
            <div class="stat-label">监控中</div>
            <div class="stat-trend">
              <el-icon><Menu /></el-icon>
              <span>运行</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card alert-enabled">
          <div class="stat-icon">
            <el-icon><Bell /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.alert_enabled_count || 0 }}</div>
            <div class="stat-label">告警启用</div>
            <div class="stat-trend">
              <el-icon><Menu /></el-icon>
              <span>已开启</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card alerting">
          <div class="stat-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.alerting_count || 0 }}</div>
            <div class="stat-label">告警中</div>
            <div class="stat-trend">
              <el-icon><Warning /></el-icon>
              <span>需关注</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
            <!-- Kafka环境选择器 -->
            <div class="instance-selector-compact">
              <el-select 
                v-model="selectedConfigId" 
                placeholder="选择Kafka环境"
                @change="handleConfigChange"
                size="small"
                style="width: 280px"
              >
                <el-option
                  v-for="config in kafkaConfigs"
                  :key="config.id"
                  :label="`${config.config_name} (${config.host}:${config.port})`"
                  :value="config.id"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="font-weight: 500;">{{ config.config_name }}</span>
                    <span style="color: #909399; font-size: 12px; margin-left: 20px;">
                      {{ config.host }}:{{ config.port }}
                    </span>
                  </div>
                </el-option>
              </el-select>
              
              <el-tag v-if="currentConfig" type="success" size="small">
                <el-icon><Connection /></el-icon>
                {{ currentConfig.config_name }}
              </el-tag>
            </div>
          </div>
        </template>
        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="Topic名称">
                <el-select
                  v-model="searchForm.topic_name"
                  placeholder="输入或选择topic"
                  clearable
                  filterable
                  @focus="loadTopicsList"
                  style="width: 200px"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="topic in topicsList"
                    :key="topic"
                    :label="topic"
                    :value="topic"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 140px">
                  <el-option label="全部" value="" />
                  <el-option label="活跃" value="active" />
                  <el-option label="非活跃" value="inactive" />
                  <el-option label="仅监控" value="monitored_only" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="监控开关">
                <el-select v-model="searchForm.is_monitored" placeholder="选择监控状态" clearable style="width: 120px">
                  <el-option label="全部" :value="null" />
                  <el-option label="已启用" :value="1" />
                  <el-option label="已禁用" :value="0" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="告警开关">
                <el-select v-model="searchForm.is_alert_enabled" placeholder="选择告警开关" clearable style="width: 120px">
                  <el-option label="全部" :value="null" />
                  <el-option label="已启用" :value="1" />
                  <el-option label="已禁用" :value="0" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="告警状态">
                <el-select v-model="searchForm.alert_status" placeholder="选择告警状态" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="正常" value="normal" />
                  <el-option label="告警中" value="alerting" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="search-form-actions">
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button 
                type="success" 
                @click="quickActionsExpanded = !quickActionsExpanded" 
                class="quick-actions-btn"
                plain
              >
                <el-icon>
                  <component :is="quickActionsExpanded ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                快捷操作
              </el-button>
            </div>
          </div>
          
          <!-- 快捷操作折叠区域 -->
          <transition name="quick-actions">
            <div v-show="quickActionsExpanded" class="quick-actions-section">
              <div class="quick-actions-toolbar">
                <div class="toolbar-left">
                  <!-- 选中记录时显示徽章和所有批量操作按钮 -->
                  <template v-if="selectedMonitors.length > 0">
                    <div class="selected-info-inline">
                      <el-icon class="selected-icon"><Select /></el-icon>
                      <span>已选择 <strong>{{ selectedMonitors.length }}</strong> 条记录</span>
                    </div>
                    
                    <el-divider direction="vertical" />
                    
                    <!-- 所有批量操作按钮 -->
                    <div class="button-group">
                      <el-button 
                        @click="showBatchUpdateAlert" 
                        class="btn-alert-config"
                        :disabled="!selectedConfigId"
                      >
                        <el-icon><BellFilled /></el-icon>
                        批量更新告警配置
                      </el-button>
                      
                      <el-button type="success" @click="handleBatchEnableMonitor">
                        <el-icon><View /></el-icon>
                        启用监控
                      </el-button>
                      
                      <el-button type="warning" @click="handleBatchDisableMonitor">
                        <el-icon><Hide /></el-icon>
                        禁用监控
                      </el-button>
                      
                      <el-button type="primary" @click="handleBatchEnableAlert">
                        <el-icon><Bell /></el-icon>
                        启用告警
                      </el-button>
                      
                      <el-button type="info" @click="handleBatchDisableAlert">
                        <el-icon><TurnOff /></el-icon>
                        禁用告警
                      </el-button>
                      
                      <el-button type="danger" @click="handleBatchDelete">
                        <el-icon><Delete /></el-icon>
                        批量删除
                      </el-button>
                    </div>
                  </template>
                  
                  <!-- 未选中时只显示批量更新告警配置按钮 -->
                  <template v-else>
                    <div class="button-group">
                      <el-button 
                        @click="showBatchUpdateAlert" 
                        class="btn-alert-config"
                        :disabled="!selectedConfigId"
                      >
                        <el-icon><BellFilled /></el-icon>
                        批量更新告警配置
                      </el-button>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </transition>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>监控列表</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="loading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <div class="table-info">
                <!-- 合并的分页信息控制 -->
                <div class="pagination-control-wrapper" @click="paginationExpanded = !paginationExpanded">
                  <span class="page-count">本页 {{ monitors.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">{{ currentPage }}/{{ Math.ceil(total / pageSize) || 1 }}</span>
                  <el-icon class="pagination-icon" :class="{ 'expanded': paginationExpanded }">
                    <ArrowDown />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>
        <div class="table-container">
      <el-table
        :data="monitors"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'last_alert_time', order: 'descending' }"
        style="width: 100%"
        :height="600"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="topic_name" label="Topic名称" width="350" fixed="left">
          <template #default="{ row }">
            <div class="topic-name-cell">
              <span class="topic-text">{{ row.topic_name }}</span>
              <el-tooltip content="复制Topic名称" placement="top">
                <el-button 
                  type="info"
                  size="small" 
                  @click="handleCopyTopicName(row.topic_name)" 
                  circle
                  class="copy-btn"
                >
                  <el-icon><DocumentCopy /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="latest_offset" label="最新Offset" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ row.latest_offset }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message_timestamp" label="最新消息时间" width="180" sortable="custom">
          <template #default="{ row }">
            <span v-if="row.message_timestamp">{{ formatTime(row.message_timestamp) }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_monitored" label="监控开关" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_monitored"
              :active-value="1"
              :inactive-value="0"
              @change="handleToggleMonitor(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="is_alert_enabled" label="告警开关" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_alert_enabled"
              :active-value="1"
              :inactive-value="0"
              @change="handleToggleAlert(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="alert_status" label="告警状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getAlertStatusType(row.alert_status)"
              size="small"
            >
              {{ getAlertStatusText(row.alert_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="alert_threshold_hours" label="告警阈值(小时)" width="130" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_alert_time" label="最后告警时间" width="180" sortable="custom">
          <template #default="{ row }">
            <span v-if="row.last_alert_time">{{ formatTime(row.last_alert_time) }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看详情" placement="top">
                <el-button 
                  type="primary"
                  size="small" 
                  @click="handleViewDetail(row)" 
                  circle
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="编辑配置" placement="top">
                <el-button 
                  type="warning"
                  size="small" 
                  @click="handleEdit(row)" 
                  circle
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip 
                v-if="row.alert_status === 'alerting'"
                content="重置告警" 
                placement="top"
              >
                <el-button 
                  type="success"
                  size="small" 
                  @click="handleResetAlert(row)" 
                  circle
                >
                  <el-icon><RefreshRight /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="立即查询" placement="top">
                <el-button 
                  type="info"
                  size="small" 
                  @click="handleQueryNow(row)" 
                  circle
                >
                  <el-icon><Search /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
        </div>
        
        <!-- 分页折叠区域 -->
        <transition name="pagination-slide">
          <div v-show="paginationExpanded" class="pagination-section">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      width="900px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><View /></el-icon>
          </div>
          <div class="header-content">
            <h3>监控详情</h3>
            <p>{{ currentMonitor?.topic_name }}</p>
          </div>
        </div>
      </template>
      
      <div v-if="currentMonitor" class="monitor-detail dialog-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ currentMonitor.id }}</el-descriptions-item>
          <el-descriptions-item label="配置ID">{{ currentMonitor.config_id }}</el-descriptions-item>
          <el-descriptions-item label="Topic名称">{{ currentMonitor.topic_name }}</el-descriptions-item>
          <el-descriptions-item label="监控维度">
            <el-tag :type="currentMonitor.partition_id === -1 ? 'success' : 'info'" size="small">
              {{ currentMonitor.partition_id === -1 ? 'Topic级别' : `分区${currentMonitor.partition_id}` }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最新Offset">{{ currentMonitor.latest_offset }}</el-descriptions-item>
          <el-descriptions-item label="消费滞后">{{ currentMonitor.consumer_lag }}</el-descriptions-item>
          <el-descriptions-item label="最新消息时间">{{ formatTime(currentMonitor.message_timestamp) }}</el-descriptions-item>
          <el-descriptions-item label="消息Key">{{ currentMonitor.message_key || '-' }}</el-descriptions-item>
          <el-descriptions-item label="Topic大小">{{ (currentMonitor.topic_size_bytes / 1024 / 1024).toFixed(2) }} MB</el-descriptions-item>
          <el-descriptions-item label="监控状态">
            <el-tag :type="currentMonitor.is_monitored ? 'success' : 'info'">
              {{ currentMonitor.is_monitored ? '已启用' : '已禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="告警启用">
            <el-tag :type="currentMonitor.is_alert_enabled ? 'success' : 'info'">
              {{ currentMonitor.is_alert_enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="告警阈值">{{ currentMonitor.alert_threshold_hours }} 小时</el-descriptions-item>
          <el-descriptions-item label="Webhook URL" :span="2">
            <span class="text-muted">{{ currentMonitor.webhook_url || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentMonitor.status)">
              {{ getStatusText(currentMonitor.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="告警状态">
            <el-tag :type="getAlertStatusType(currentMonitor.alert_status)">
              {{ getAlertStatusText(currentMonitor.alert_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="告警次数">{{ currentMonitor.alert_count }}</el-descriptions-item>
          <el-descriptions-item label="最大告警次数">{{ currentMonitor.max_alert_count }}</el-descriptions-item>
          <el-descriptions-item label="首次告警时间">{{ formatTime(currentMonitor.first_alert_time) }}</el-descriptions-item>
          <el-descriptions-item label="最后告警时间">{{ formatTime(currentMonitor.last_alert_time) }}</el-descriptions-item>
          <el-descriptions-item label="告警发送时间">{{ currentMonitor.alert_first_send_time }}</el-descriptions-item>
          <el-descriptions-item label="第2次告警间隔">{{ currentMonitor.alert_second_interval }} 秒</el-descriptions-item>
          <el-descriptions-item label="第3次告警间隔">{{ currentMonitor.alert_third_interval }} 秒</el-descriptions-item>
          <el-descriptions-item label="告警历史ID">{{ currentMonitor.alert_history_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(currentMonitor.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(currentMonitor.updated_at) }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 最新消息内容区域 -->
        <div v-if="currentMonitor.latest_message" class="latest-message">
          <div class="message-header">
            <h4>最新消息内容</h4>
            <div class="message-actions">
              <el-tooltip content="复制JSON" placement="top">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleCopyJson"
                  circle
                >
                  <el-icon><CopyDocument /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
          
          <div class="json-viewer">
            <pre><code>{{ formatJsonMessage(currentMonitor.latest_message) }}</code></pre>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 批量更新告警配置对话框 -->
    <el-dialog
      v-model="showBatchAlertDialog"
      width="700px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-warning">
            <el-icon><BellFilled /></el-icon>
          </div>
          <div class="header-content">
            <h3>批量更新告警配置</h3>
            <p>更新选中 {{ batchAlertForm.selectedCount }} 条记录的告警配置</p>
          </div>
        </div>
      </template>
      
      <div class="dialog-content">
        <el-form :model="batchAlertForm" label-width="140px">
          <el-form-item label="更新范围:">
            <el-radio-group v-model="batchAlertForm.updateScope">
              <el-radio 
                label="selected" 
                :disabled="selectedMonitors.length === 0"
              >
                仅更新选中的 {{ selectedMonitors.length }} 条记录
              </el-radio>
              <el-radio label="all">更新当前环境的全部记录（共{{ total }}条）</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-divider />
          
          <el-form-item label="告警阈值(小时):">
            <el-input-number 
              v-model="batchAlertForm.alert_threshold_hours" 
              :min="1" 
              :max="168"
              placeholder="请输入告警阈值"
              style="width: 200px"
            />
            <span style="margin-left: 10px; color: #909399;">小时无新消息则触发告警</span>
          </el-form-item>
          
          <el-form-item label="Webhook URL:">
            <el-input 
              v-model="batchAlertForm.webhook_url" 
              placeholder="请输入企业微信/钉钉Webhook地址"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="首次告警时间:">
            <el-time-select
              v-model="batchAlertForm.alert_first_send_time"
              start="00:00"
              step="00:30"
              end="23:30"
              placeholder="选择首次告警发送时间"
              style="width: 200px"
              popper-class="batch-dialog-select-popper"
              :teleported="true"
            />
            <span style="margin-left: 10px; color: #909399;">建议设置在上班时间</span>
          </el-form-item>
          
          <el-form-item label="第2次告警间隔:">
            <el-input-number 
              v-model="batchAlertForm.alert_second_interval" 
              :min="60" 
              :max="86400"
              :step="3600"
              placeholder="秒"
              style="width: 200px"
            />
            <span v-if="batchAlertForm.alert_second_interval" style="margin-left: 10px; color: #909399;">
              秒（{{ formatSeconds(batchAlertForm.alert_second_interval) }}）
            </span>
            <span v-else style="margin-left: 10px; color: #909399;">秒</span>
          </el-form-item>
          
          <el-form-item label="第3次告警间隔:">
            <el-input-number 
              v-model="batchAlertForm.alert_third_interval" 
              :min="60" 
              :max="86400"
              :step="3600"
              placeholder="秒"
              style="width: 200px"
            />
            <span v-if="batchAlertForm.alert_third_interval" style="margin-left: 10px; color: #909399;">
              秒（{{ formatSeconds(batchAlertForm.alert_third_interval) }}）
            </span>
            <span v-else style="margin-left: 10px; color: #909399;">秒</span>
          </el-form-item>
          
          <el-form-item label="最大告警次数:">
            <el-input-number 
              v-model="batchAlertForm.max_alert_count" 
              :min="1" 
              :max="10"
              placeholder="次"
              style="width: 200px"
            />
            <span style="margin-left: 10px; color: #909399;">单周期内最多发送告警次数</span>
          </el-form-item>
          
          <el-alert
            title="提示"
            type="info"
            :closable="false"
            style="margin-top: 16px"
          >
            <ul style="margin: 0; padding-left: 20px;">
              <li>只有填写的字段才会被更新，留空的字段保持原值不变</li>
              <li>批量更新不会修改监控开关和告警开关状态</li>
              <li>告警间隔时间从首次告警开始计算</li>
            </ul>
          </el-alert>
        </el-form>
      </div>
      
      <template #footer>
        <el-button @click="showBatchAlertDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleBatchUpdateAlertConfig" 
          :loading="batchAlertForm.loading"
        >
          确认更新
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <MonitorEditDialog
      v-model="showEditDialog"
      :monitor="currentMonitor"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useKafkaMonitorStore } from '@/stores/kafkaMonitor'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, ArrowUp, BellFilled, Select, CopyDocument, DocumentCopy, QuestionFilled } from '@element-plus/icons-vue'
import { componentLogger } from '@/utils/logger'
import { copyToClipboard as copyText } from '@/utils/clipboard'
import dayjs from 'dayjs'
import MonitorEditDialog from './components/MonitorEditDialog.vue'

const kafkaMonitorStore = useKafkaMonitorStore()

// 响应式数据
const monitors = computed(() => kafkaMonitorStore.monitors)
const loading = computed(() => kafkaMonitorStore.loading)
const total = computed(() => kafkaMonitorStore.total)
const stats = computed(() => kafkaMonitorStore.stats)
const searchForm = computed(() => kafkaMonitorStore.searchForm)
const currentPage = computed({
  get: () => kafkaMonitorStore.currentPage,
  set: (val) => { kafkaMonitorStore.currentPage = val }
})
const pageSize = computed({
  get: () => kafkaMonitorStore.pageSize,
  set: (val) => { kafkaMonitorStore.pageSize = val }
})

// 本地状态
const selectedMonitors = ref([])
const showEditDialog = ref(false)
const currentMonitor = ref(null)
const kafkaConfigs = ref([])
const selectedConfigId = ref(null)
const topicsList = ref([]) // Topic列表（用于下拉选择）
const paginationExpanded = ref(false) // 分页折叠控制
const quickActionsExpanded = ref(false) // 快捷操作折叠控制
const showBatchAlertDialog = ref(false) // 批量更新告警配置对话框
const currentConfig = computed(() => {
  return kafkaConfigs.value.find(c => c.id === selectedConfigId.value)
})

// 监听选中表格的变化，自动展开/折叠快捷操作
watch(() => selectedMonitors.value.length, (newLength) => {
  if (newLength > 0) {
    // 有选中表格时，自动展开快捷操作
    quickActionsExpanded.value = true
  } else {
    // 取消选中时，自动折叠快捷操作
    quickActionsExpanded.value = false
  }
})

// 批量更新告警配置表单
const batchAlertForm = ref({
  updateScope: 'selected',
  alert_threshold_hours: null,
  webhook_url: '',
  alert_first_send_time: '',
  alert_second_interval: null,
  alert_third_interval: null,
  max_alert_count: null,
  selectedCount: 0,
  loading: false
})

// 固定容器样式（不响应侧边栏折叠）
const containerStyle = {
  padding: '0'
}

// 计算表格最大高度
const tableMaxHeight = computed(() => {
  return window.innerHeight - 500
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 获取告警状态类型
const getAlertStatusType = (status) => {
  const typeMap = {
    'normal': 'success',
    'alerting': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取告警状态文本
const getAlertStatusText = (status) => {
  const textMap = {
    'normal': '正常',
    'alerting': '告警中'
  }
  return textMap[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'active': 'success',       // 绿色 - 监控+告警都开启
    'inactive': 'info',        // 灰色 - 监控+告警都关闭
    'monitored_only': 'warning' // 橙色 - 仅监控开启
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'active': '活跃',          // 监控+告警都开启
    'inactive': '非活跃',      // 监控+告警都关闭
    'monitored_only': '仅监控' // 仅监控开启，告警关闭
  }
  return textMap[status] || status
}

// 加载Kafka配置列表
const loadKafkaConfigs = async () => {
  try {
    const response = await kafkaMonitorStore.fetchKafkaConfigs()
    if (response && response.success && response.data) {
      kafkaConfigs.value = response.data
      
      // 从localStorage恢复上次选择的配置
      const savedConfigId = localStorage.getItem('kafka_monitor_config_id')
      if (savedConfigId && kafkaConfigs.value.find(c => c.id == savedConfigId)) {
        selectedConfigId.value = parseInt(savedConfigId)
      } else if (kafkaConfigs.value.length > 0) {
        // 默认选择第一个配置
        selectedConfigId.value = kafkaConfigs.value[0].id
      }
      
      componentLogger.info('加载Kafka配置成功', { 
        count: kafkaConfigs.value.length, 
        selectedId: selectedConfigId.value 
      })
    }
  } catch (error) {
    componentLogger.error('加载Kafka配置失败:', error)
    ElMessage.error('加载Kafka配置失败')
  }
}

// 环境切换处理
const handleConfigChange = async (configId) => {
  componentLogger.info('切换Kafka环境:', configId)
  selectedConfigId.value = configId
  // 保存到localStorage
  localStorage.setItem('kafka_monitor_config_id', configId)
  
  // 重置页码、清空Topic列表并重新加载数据
  currentPage.value = 1
  topicsList.value = [] // 清空Topic列表，切换环境后重新加载
  
  try {
    await loadMonitors()
    // 切换环境后立即加载新环境的Topic列表
    await loadTopicsList()
    ElMessage.success(`已切换到: ${currentConfig.value?.config_name || ''}`)
  } catch (error) {
    componentLogger.error('切换配置后加载数据失败:', error)
    ElMessage.error('切换配置失败')
  }
}

const loadMonitors = async () => {
  if (!selectedConfigId.value) {
    componentLogger.warn('未选择Kafka环境')
    return
  }
  
  try {
    await kafkaMonitorStore.fetchMonitors(selectedConfigId.value)
  } catch (error) {
    componentLogger.error('加载监控数据失败:', error)
  }
}

// 加载Topic列表（从后端API获取完整列表）
const loadTopicsList = async () => {
  if (!selectedConfigId.value) {
    componentLogger.warn('未选择Kafka环境，无法加载Topic列表')
    return
  }
  
  try {
    const response = await kafkaMonitorStore.fetchTopicsList(selectedConfigId.value)
    if (response && response.success) {
      topicsList.value = response.data || []
      componentLogger.info('加载Topic列表成功', { count: topicsList.value.length })
    }
  } catch (error) {
    componentLogger.error('加载Topic列表失败:', error)
    // 失败时作为后备方案，从当前监控数据中提取
    if (monitors.value.length > 0) {
      const topics = [...new Set(monitors.value.map(m => m.topic_name))].sort()
      topicsList.value = topics
      componentLogger.info('使用后备方案从当前数据提取Topic列表', { count: topics.length })
    }
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadMonitors()
}

// 重置
const handleReset = () => {
  kafkaMonitorStore.resetSearch()
  loadMonitors()
}

// 刷新
const handleRefresh = () => {
  loadMonitors()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedMonitors.value = selection
}

// 排序变化
const handleSortChange = ({ prop, order }) => {
  if (prop) {
    kafkaMonitorStore.sortField = prop
    kafkaMonitorStore.sortOrder = order === 'ascending' ? 'asc' : 'desc'
    loadMonitors()
  }
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  loadMonitors()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadMonitors()
}

// 切换监控状态
const handleToggleMonitor = async (row) => {
  const originalMonitored = row.is_monitored
  const originalAlertEnabled = row.is_alert_enabled
  const originalStatus = row.status
  
  try {
    // 计算新的状态
    let newStatus = 'inactive'
    let updateData = {
      is_monitored: row.is_monitored
    }
    
    // 如果关闭监控，联动关闭告警
    if (row.is_monitored === 0) {
      row.is_alert_enabled = 0  // 联动关闭告警开关
      updateData.is_alert_enabled = 0
      newStatus = 'inactive'
    } else {
      // 如果打开监控，根据告警开关状态计算status
      if (row.is_alert_enabled === 1) {
        newStatus = 'active'
      } else {
        newStatus = 'monitored_only'
      }
    }
    
    updateData.status = newStatus
    row.status = newStatus  // 立即更新UI显示
    
    await kafkaMonitorStore.updateMonitor(row.id, updateData)
    ElMessage.success('监控开关已更新')
  } catch (error) {
    // 回滚到原值
    row.is_monitored = originalMonitored
    row.is_alert_enabled = originalAlertEnabled
    row.status = originalStatus
    ElMessage.error('更新失败')
  }
}

// 切换告警状态
const handleToggleAlert = async (row) => {
  const originalAlertEnabled = row.is_alert_enabled
  const originalStatus = row.status
  
  try {
    // 如果监控未开启，不允许单独开启告警
    if (row.is_monitored === 0 && row.is_alert_enabled === 1) {
      ElMessage.warning('请先开启监控开关')
      row.is_alert_enabled = 0
      return
    }
    
    // 计算新的状态
    let newStatus = 'inactive'
    if (row.is_monitored === 1) {
      if (row.is_alert_enabled === 1) {
        newStatus = 'active'
      } else {
        newStatus = 'monitored_only'
      }
    }
    
    row.status = newStatus  // 立即更新UI显示
    
    await kafkaMonitorStore.updateMonitor(row.id, {
      is_alert_enabled: row.is_alert_enabled,
      status: newStatus
    })
    ElMessage.success('告警开关已更新')
  } catch (error) {
    // 回滚到原值
    row.is_alert_enabled = originalAlertEnabled
    row.status = originalStatus
    ElMessage.error('更新失败')
  }
}

// 编辑
// 查看详情
const showDetailDialog = ref(false)

const handleViewDetail = (row) => {
  currentMonitor.value = { ...row }
  showDetailDialog.value = true
}

// 格式化JSON消息
const formatJsonMessage = (message) => {
  if (!message) {
    return '暂无消息内容'
  }
  
  try {
    // 如果是字符串，尝试解析
    if (typeof message === 'string') {
      const parsed = JSON.parse(message)
      return JSON.stringify(parsed, null, 2)
    }
    // 如果已经是对象，直接格式化
    return JSON.stringify(message, null, 2)
  } catch (e) {
    // 解析失败，返回原始内容
    componentLogger.warn('Failed to parse message:', e)
    return typeof message === 'string' ? message : JSON.stringify(message)
  }
}

// 复制JSON内容 - 使用统一工具
const handleCopyJson = async () => {
  const jsonText = formatJsonMessage(currentMonitor.value.latest_message)
  await copyText(jsonText, 'JSON内容')
}

// 复制Topic名称 - 使用统一工具
const handleCopyTopicName = async (topicName) => {
  await copyText(topicName, 'Topic名称', false)
  ElMessage.success({
    message: `Topic名称已复制: ${topicName}`,
    duration: 2000
  })
}

const handleEdit = (row) => {
  currentMonitor.value = { ...row }
  showEditDialog.value = true
}

// 显示批量更新告警配置对话框
const showBatchUpdateAlert = () => {
  // 检查是否选择了环境
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择Kafka环境')
    return
  }
  
  // 重置表单，如果没有选中记录，默认为"全部更新"模式
  const hasSelection = selectedMonitors.value.length > 0
  batchAlertForm.value = {
    updateScope: hasSelection ? 'selected' : 'all',
    alert_threshold_hours: null,
    webhook_url: '',
    alert_first_send_time: '',
    alert_second_interval: null,
    alert_third_interval: null,
    max_alert_count: null,
    selectedCount: selectedMonitors.value.length,
    loading: false
  }
  
  showBatchAlertDialog.value = true
}

// 批量更新告警配置
const handleBatchUpdateAlertConfig = async () => {
  try {
    // 构建更新数据，只包含用户填写的字段
    const updateData = {}
    
    if (batchAlertForm.value.alert_threshold_hours !== null) {
      updateData.alert_threshold_hours = batchAlertForm.value.alert_threshold_hours
    }
    if (batchAlertForm.value.webhook_url) {
      updateData.webhook_url = batchAlertForm.value.webhook_url
    }
    if (batchAlertForm.value.alert_first_send_time) {
      updateData.alert_first_send_time = batchAlertForm.value.alert_first_send_time
    }
    if (batchAlertForm.value.alert_second_interval !== null) {
      updateData.alert_second_interval = batchAlertForm.value.alert_second_interval
    }
    if (batchAlertForm.value.alert_third_interval !== null) {
      updateData.alert_third_interval = batchAlertForm.value.alert_third_interval
    }
    if (batchAlertForm.value.max_alert_count !== null) {
      updateData.max_alert_count = batchAlertForm.value.max_alert_count
    }
    
    if (Object.keys(updateData).length === 0) {
      ElMessage.warning('请至少填写一个字段')
      return
    }
    
    const scope = batchAlertForm.value.updateScope
    let targetIds = []
    let configId = null
    let confirmMessage = ''
    
    if (scope === 'selected') {
      targetIds = selectedMonitors.value.map(m => m.id)
      confirmMessage = `确认要更新选中的 ${targetIds.length} 条记录吗？`
    } else {
      // 更新当前环境的全部记录，传递 config_id 给后端
      configId = selectedConfigId.value
      confirmMessage = `确认要更新当前环境的全部 ${total.value} 条记录吗？\n\n此操作将更新该环境下所有Topic的告警配置。`
    }
    
    await ElMessageBox.confirm(confirmMessage, '批量更新确认', {
      type: 'warning',
      confirmButtonText: '确认更新',
      cancelButtonText: '取消'
    })
    
    batchAlertForm.value.loading = true
    
    const response = await kafkaMonitorStore.batchUpdateMonitors(targetIds, updateData, configId)
    
    if (response && response.success) {
      ElMessage.success(`批量更新成功：${response.message || '操作完成'}`)
      showBatchAlertDialog.value = false
      await loadMonitors()
    }
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('批量更新告警配置失败:', error)
      ElMessage.error('批量更新失败')
    }
  } finally {
    batchAlertForm.value.loading = false
  }
}

// 格式化秒数为可读时间
const formatSeconds = (seconds) => {
  if (!seconds) return ''
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (hours > 0) {
    return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`
  }
  return `${minutes}分钟`
}

// 编辑成功
const handleEditSuccess = () => {
  loadMonitors()
}

// 删除
// 立即查询单个topic
const handleQueryNow = async (row) => {
  try {
    ElMessage.success(`正在查询 ${row.topic_name}[分区${row.partition_id}] 的最新数据...`)
    
    const response = await kafkaMonitorStore.queryTopicNow(row.config_id, row.topic_name, row.partition_id)
    
    if (response && response.success) {
      ElMessage.success('查询成功，数据已更新')
      // 刷新列表显示最新数据
      await loadMonitors()
    } else {
      ElMessage.error('查询失败: ' + (response?.message || '未知错误'))
    }
  } catch (error) {
    componentLogger.error('立即查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  }
}

// 重置告警
const handleResetAlert = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置 "${row.topic_name}[${row.partition_id}]" 的告警状态吗？`,
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await kafkaMonitorStore.resetAlertStatus(row.id)
    loadMonitors()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('重置告警失败:', error)
    }
  }
}

// ========== 批量操作（无论是否选中都显示） ==========

// 批量启用监控
const handleBatchEnableMonitor = async () => {
  try {
    const ids = selectedMonitors.value.map(m => m.id)
    await kafkaMonitorStore.batchUpdateMonitors(ids, { is_monitored: 1 })
    loadMonitors()
  } catch (error) {
    componentLogger.error('批量启用监控失败:', error)
  }
}

// 批量禁用监控
const handleBatchDisableMonitor = async () => {
  try {
    const ids = selectedMonitors.value.map(m => m.id)
    await kafkaMonitorStore.batchUpdateMonitors(ids, { is_monitored: 0 })
    loadMonitors()
  } catch (error) {
    componentLogger.error('批量禁用监控失败:', error)
  }
}

// 批量启用告警
const handleBatchEnableAlert = async () => {
  try {
    const ids = selectedMonitors.value.map(m => m.id)
    await kafkaMonitorStore.batchUpdateMonitors(ids, { is_alert_enabled: 1 })
    loadMonitors()
  } catch (error) {
    componentLogger.error('批量启用告警失败:', error)
  }
}

// 批量禁用告警
const handleBatchDisableAlert = async () => {
  try {
    const ids = selectedMonitors.value.map(m => m.id)
    await kafkaMonitorStore.batchUpdateMonitors(ids, { is_alert_enabled: 0 })
    loadMonitors()
  } catch (error) {
    componentLogger.error('批量禁用告警失败:', error)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedMonitors.value.length} 条监控记录吗？此操作不可撤销！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedMonitors.value.map(m => m.id)
    await kafkaMonitorStore.batchDeleteMonitors(ids)
    loadMonitors()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('批量删除失败:', error)
    }
  }
}

// 生命周期
onMounted(async () => {
  try {
    // 先加载配置列表
    await loadKafkaConfigs()
    
    // 如果已选择配置，则加载数据和Topic列表
    if (selectedConfigId.value) {
      await loadMonitors()
      await loadTopicsList()
    }
  } catch (error) {
    componentLogger.error('初始化页面失败:', error)
  }
})
</script>

<style scoped>
.kafka-monitor-container {
  padding: 0;
}

/* 页面头部样式 */
.page-header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  border-radius: 12px;
  overflow: hidden;
  color: #303133;
  min-height: 120px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}

.bg-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  opacity: 1;
}

.bg-pattern {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 80%, rgba(255, 152, 0, 0.05) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 152, 0, 0.05) 0%, transparent 50%);
  animation: patternMove 30s ease-in-out infinite;
}

@keyframes patternMove {
  0%, 100% { transform: translateX(0) translateY(0); }
  25% { transform: translateX(-10px) translateY(-5px); }
  50% { transform: translateX(5px) translateY(-10px); }
  75% { transform: translateX(-5px) translateY(5px); }
}

.page-title {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  gap: 24px;
  flex: 1;
}

.title-icon {
  position: relative;
}

.page-header .title-icon .icon-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px !important;
  height: 36px !important;
  background: linear-gradient(135deg, #ff9800 0%, #ffb74d 100%) !important;
  border-radius: 8px !important;
  color: white !important;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(255, 152, 0, 0.2) !important;
}

.page-header .title-icon .icon-container:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(255, 152, 0, 0.3) !important;
}

.page-header .title-icon .icon-glow {
  position: absolute;
  top: -4px;
  left: -4px;
  right: -4px;
  bottom: -4px;
  background: linear-gradient(45deg, rgba(255, 152, 0, 0.2), rgba(255, 183, 77, 0.3));
  border-radius: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.page-header .title-icon .icon-container:hover .icon-glow {
  opacity: 1;
}

.title-content {
  flex: 1;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.title-main h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  letter-spacing: -0.3px;
}

.title-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  color: white;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.page-description {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-meta {
  display: flex;
  gap: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 12px;
  font-weight: 500;
}

.page-stats {
  position: relative;
  z-index: 1;
  display: flex;
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 120px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stat-card:hover {
  background: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.stat-card:hover::before {
  opacity: 1;
}

.stat-icon {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.stat-card.active .stat-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.stat-card.monitored .stat-icon {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.stat-card.alert-enabled .stat-icon {
  background: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}

.stat-card.alerting .stat-icon {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  color: #909399;
  font-weight: 500;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 24px;
}

.search-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.search-title .el-icon {
  color: #409eff;
}

.instance-selector-compact {
  display: flex;
  align-items: center;
  gap: 12px;
}

.instance-selector-compact .el-tag {
  font-weight: 500;
}

.search-form {
  margin: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.search-form-fields {
  display: flex;
  gap: 16px;
  flex: 1;
}

.search-form-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 表格区域 */
.table-section {
  margin-bottom: 24px;
}

.table-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-title .el-icon {
  color: #409eff;
}

.table-header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-icon {
  font-size: 12px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-icon.expanded {
  transform: rotate(180deg);
}

.table-container {
  margin: -16px -16px 0;
}

/* 分页区域 */
.pagination-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.pagination-section .el-pagination {
  display: flex;
  justify-content: center;
}

/* 分页折叠动画 */
.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.pagination-slide-enter-to,
.pagination-slide-leave-from {
  opacity: 1;
  max-height: 200px;
}

/* 按钮样式 */
.refresh-btn {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

/* 快捷操作按钮 */
.quick-actions-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 快捷操作区域 */
.quick-actions-section {
  margin-top: 16px;
  padding: 16px;
  border-top: 2px solid #409eff;
  border-radius: 8px;
}

.quick-actions-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
  flex-wrap: wrap;
}

.selected-info-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #409eff;
}

.selected-info-inline .selected-icon {
  font-size: 16px;
}

.selected-info-inline strong {
  color: #409eff;
  font-size: 16px;
}

.button-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.button-group .el-button {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.btn-alert-config {
  background: linear-gradient(135deg, #e6a23c 0%, #f0c78a 100%);
  border: none;
  color: #fff;
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.3);
}

.btn-alert-config:hover {
  background: linear-gradient(135deg, #f0c78a 0%, #e6a23c 100%);
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

.btn-reset {
  background: linear-gradient(135deg, #67c23a 0%, #95d475 100%);
  border: none;
  color: #fff;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.btn-reset:hover {
  background: linear-gradient(135deg, #95d475 0%, #67c23a 100%);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

/* 帮助图标 */
.help-icon {
  margin-left: 8px;
  color: #909399;
  cursor: help;
  font-size: 16px;
}

.help-icon:hover {
  color: #409eff;
}

/* 快捷操作折叠动画 */
.quick-actions-enter-active,
.quick-actions-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.quick-actions-enter-from,
.quick-actions-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
}

.quick-actions-enter-to,
.quick-actions-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 500px;
}

.text-muted {
  color: #909399;
}

/* 操作按钮样式 - 与StarRocks Tables保持一致 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  white-space: nowrap;
  justify-content: flex-start;
  align-items: center;
  min-width: 200px;
}

.action-buttons .el-button {
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.action-buttons .el-button:active {
  transform: translateY(0) scale(0.98);
}

.action-buttons .el-button--primary {
  background: linear-gradient(135deg, #409EFF 0%, #66B3FF 100%);
  border: none;
}

.action-buttons .el-button--success {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
}

.action-buttons .el-button--warning {
  background: linear-gradient(135deg, #E6A23C 0%, #F0C78A 100%);
  border: none;
}

.action-buttons .el-button--danger {
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
  border: none;
}

.action-buttons .el-button--info {
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
  border: none;
}

/* 详情对话框样式 */
.monitor-detail {
  padding: 0;
}

.monitor-detail .el-descriptions {
  margin-bottom: 24px;
}

.monitor-detail :deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  background-color: #fafafa;
}

.monitor-detail :deep(.el-descriptions__content) {
  color: #303133;
}

.latest-message {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.latest-message h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.latest-message h4::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #409eff 0%, #79bbff 100%);
  border-radius: 2px;
}

.message-actions {
  display: flex;
  gap: 8px;
}

.message-actions .el-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.message-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* JSON查看器 */
.json-viewer {
  margin-top: 12px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.json-viewer pre {
  margin: 0;
  padding: 16px;
  overflow-x: auto;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 13px;
  line-height: 1.6;
  color: #303133;
  background: transparent;
}

.json-viewer code {
  background: transparent;
  color: inherit;
  padding: 0;
  font-family: inherit;
}

.json-viewer pre::-webkit-scrollbar {
  height: 8px;
}

.json-viewer pre::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.json-viewer pre::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.json-viewer pre::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* Topic名称列样式 */
.topic-name-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
}

.topic-text {
  flex: 1;
  white-space: nowrap;
  font-size: 14px;
  font-weight: 400;
  color: #303133;
  line-height: 1.4;
}

.topic-name-cell .copy-btn {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  padding: 0;
  opacity: 0;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
  border: none;
}

.topic-name-cell:hover .copy-btn {
  opacity: 1;
}

.topic-name-cell .copy-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.topic-name-cell .copy-btn:active {
  transform: scale(0.95);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .page-stats {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .page-stats {
    flex-wrap: wrap;
  }
  
  .search-form-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form-fields {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
  
  .batch-actions-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .batch-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>

